﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Glossary;

namespace Teacher
{
    /// <summary>
    /// Ansvar: Kim Nielsen
    /// </summary>
    public partial class TeacherGUI : Form
    {
        private WordLibrary myWordLibrary = new WordLibrary();
        private Language language = Language.English;

        public TeacherGUI()
        {
            InitializeComponent();
            
            //Hämtar default språk(engelska) i gränssnittet.
            FillListView(language);
            labelCurrentLanguage.Text = language.ToString();
            labelGlosa.Text = language.ToString();
            radioButtonEngelska.Checked = true;

            ListCoursesInCourseComboBox();
        }

        /// <summary>
        /// Ansvar: Kim Nielsen
        /// Radioknappar för att sätta språk
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButtonEngelska_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonEngelska.Checked)
            {
                language = Language.English;
                FillListView(language);
                buttonAddWord.Enabled = true;
                buttonSaveTxtFile.Enabled = true;
                //Label till aktuellt språk
                labelCurrentLanguage.Text = language.ToString();
                labelGlosa.Text = "Engelsk glosa";
            }

        }
        private void radioButtonGerman_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonGerman.Checked)
            {
                language = Language.German;
                FillListView(language);
                buttonAddWord.Enabled = true;
                buttonGenerateTest.Enabled = true;
                buttonSaveTxtFile.Enabled = true;
                //Label till aktuellt språk
                labelCurrentLanguage.Text = language.ToString();
                labelGlosa.Text = "Tysk glosa";

            }

        }
        private void radioButtonSpanish_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonSpanish.Checked)
            {
                language = Language.Spanish;
                FillListView(language);
                buttonAddWord.Enabled = true;
                buttonSaveTxtFile.Enabled = true;
                //Label till aktuellt språk
                labelCurrentLanguage.Text = language.ToString();
                labelGlosa.Text = "Spansk glosa";
            }

        }

        /// <summary>
        /// Lägger till glosa i wordLibrary och skriver ut i listviewn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddWord_Click_1(object sender, EventArgs e)
        {
            string swedishWord = textBoxSvensktOrd.Text;
            string foreignWord = textBoxGlosa.Text;
            string description = textBoxDescription.Text;
            if (foreignWord != "" && swedishWord != "")
            {
                Word word = new Word(foreignWord, swedishWord, description, language);
                IODatabase.WriteNewWordToDataSource(word);
            }
            else
            {
                MessageBox.Show("Skriv in svenskt ord och glosa!");
            }

            FillListView(language);
            textBoxSvensktOrd.Clear();
            textBoxGlosa.Clear();
            textBoxDescription.Clear();

        }

        /// <summary>
        /// Ansvar: Kim Nielsen
        /// Läs in glosfil till WordLibrary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonReadFromFile_Click(object sender, EventArgs e)
        {
            try
            {
                //Filtrerar och visar enbart filer av typen .txt
                openFileDialog.Filter = "TXT|*txt";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Sökväg till fil
                    string fileName = openFileDialog.FileName;
                    //Språk på glosor
                    language = IOTextFile.LanguageOfFile(fileName);
                    //Kontrollerar språk för att sätta radioknappar
                    switch (language)
                    {
                        case Language.English:
                            radioButtonEngelska.Checked = true;
                            break;
                        case Language.German:
                            radioButtonGerman.Checked = true;
                            break;
                        case Language.Spanish:
                            radioButtonSpanish.Checked = true;
                            break;
                        default:
                            throw new Glossary.Exceptions.UnknownLanguageException();
                    }

                    //Läs in strängar från fil till WordLibrary
                    IOTextFile.ReadGlossaryFromFile(ref myWordLibrary, fileName);

                    //Skriv ut listan i ListView
                    FillListView(language);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Något gick fel vid inläsning av fil: " + ex);


            }

        }

        /// <summary>
        /// Ansvar: Kim Nielsen
        /// Sparar ny glosfil av WordLibrary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSaveTxtFile_Click(object sender, EventArgs e)
        {
            List<Word> libraryList = myWordLibrary.GetWordLibrary(language);
            saveFileDialog.Filter = "TXT|*.txt";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveFileDialog.FileName;
                string fileExtension = fileName.Substring(fileName.Length - 4, 4);
                if (fileExtension != ".txt")
                {
                    fileName = fileName + ".txt";
                }
                IOTextFile.WriteGlossaryToFile(libraryList, language, fileName);
                MessageBox.Show(String.Format("Glosfilen är sparad som: {0}", fileName));
            }
        }

        /// <summary>
        /// Genererar nytt glosprov .txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGenerateTest_Click(object sender, EventArgs e)
        {
            string choosenCourse = comboBoxCourse.Text;
            int numberOfWords = 0;
            int.TryParse(comboBoxNumberOfWords.Text, out numberOfWords);
            Language userLanguage = Language.English;

            if (choosenCourse == "" || numberOfWords == 0)
            {
                MessageBox.Show("Fyll i kurs och antal");
            }
            else
            {
            //    switch (choosenLanguage)
            //    {
            //        case "Engelska":
            //            {
            //                userLanguage = Language.English;
            //                break;
            //            }
            //        case "Spanska":
            //            {
            //                userLanguage = Language.Spanish;
            //                break;
            //            }
            //        case "Tyska":
            //            {
            //                userLanguage = Language.German;
            //                break;
            //            }
            //        default:
            //            throw new Glossary.Exceptions.UnknownLanguageException();
            //    }

                //Skapa vector med slumpade ord
                Word[] randomWords;
                randomWords = myWordLibrary.GetRandomWords(userLanguage, numberOfWords);

                //Skapa nytt createdTest
                CreatedTest createdTest = new CreatedTest(randomWords);
                createdTest.LanguageOfTest = userLanguage;
                createdTest.DateOfCreation = DateTime.Now;
                createdTest.CourseID = comboBoxCourse.Text;
                
                //Skriv createdtest till db
                IODatabase.WriteCreatedTestToDataSource(createdTest);

            }
        }

        /// <summary>
        /// Ansvar: Viekiet Chung
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCorrectATest_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog.Filter = "Text files (*.txt)|*txt";
                if (openFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                FilledTest filledTest = IOTextFile.ReadFilledTestFromTextFile(openFileDialog.FileName);
                CorrectedTest correctedTest = TestCorrecter.Correct(filledTest, myWordLibrary, !checkBoxCaseSenitive.Checked);

                string filePath = Path.GetFullPath("..\\..\\..\\");
                filePath += "CorrectedTests\\";
                string fileName = string.Format("{0}_{1}_{2}_{3}",
                    correctedTest.DateOfCorrection.ToShortDateString(), correctedTest.LanguageOfTest, correctedTest.Student.FirstName, correctedTest.Student.LastName);
                string fileNameTXT = fileName + ".txt";
                IOTextFile.WriteCorrectedTestToTextFile(filePath + fileNameTXT, correctedTest);
                MessageBox.Show(string.Format("Rättningen är sparad som {0}{1}", filePath, fileNameTXT));

                string fileNameHTML = fileName + ".html";
                IOTextFile.WriteCorrectedTestToHTMLFile(filePath + fileNameHTML, correctedTest);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Ansvar: Kim Nielsen
        /// Metod för att fylla listview med glosor
        /// </summary>
        /// <param name="language"></param>
        private void FillListView(Language language)
        {
            listView1.Items.Clear();
            string stringLang = language.ToString();
            IODatabase.ReadGlossaryFromDataSource(ref myWordLibrary, stringLang);
            List<Word> library = myWordLibrary.GetWordLibrary(language);

            //Skriv ut listan i ListView
            int row = 1;
            foreach (Word word in library)
            {
                string swedishWordWithDesc;
                if (word.SwedishDescription == "" || word.SwedishDescription == null)
                    swedishWordWithDesc = word.SwedishWord;
                else
                    swedishWordWithDesc = string.Format("{0} ({1})", word.SwedishWord, word.SwedishDescription);

                ListViewItem lvi = new ListViewItem(row.ToString());
                lvi.SubItems.Add(swedishWordWithDesc);
                lvi.SubItems.Add(word.ForeignWord);
                listView1.Items.Add(lvi);
                row++;
            }
        }

        /// <summary>
        /// Ansvar: Kim Nielsen
        /// </summary>
        private void ListCoursesInCourseComboBox()
        {
            List<string> courses = IODatabase.ReadCoursesFromDataSource();

            foreach (string cours in courses)
            {
                if(cours != null)
                comboBoxCourse.Items.Add(cours);
            }
        }

    }
}
